package com.module_video.popuputil;

import android.app.Activity;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lib.app.CodeUtil;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.json_deal.lib_mgson.MGson;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.http.call_back.HttpDialogCallBack;
import com.lib.http.call_back.HttpNormalCallBack;
import com.luck.picture.lib.tools.ToastManage;
import com.module_video.R;
import com.module_video.adapter.CommentExpandAdapter;
import com.module_video.bean.CircleLikesBean;
import com.module_video.bean.ShareDetailSecondReplyBean;
import com.module_video.bean.ShareDetailWebReplyBean;
import com.module_video.bean.ShareVideoDetailBean_1;
import com.module_video.bean.VideoDetailCommentBean;
import com.module_video.bean.VideoDetailSecondCommentBean;
import com.module_video.view.CommentExpandableListView;
import com.zyyoona7.popup.EasyPopup;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2020/5/21 0021.
 */

public class VideoDetailCommentPopup implements View.OnClickListener {

    private Activity activity;

    //底部文本输入框
    BottomCommentPopup commentInputPopup;

    //评论部分适配器和装载容器
    CommentExpandAdapter commentAdapter;

    private List<VideoDetailCommentBean.ObjBean.RowsBean> commentsList = new ArrayList();

    private View parentView;

    //视频信息以及装载实体类
    public String videoInfoStr;
    ShareVideoDetailBean_1.ObjBean.RowsBean videoData;

    //因一级、二级、评论都是相同输入框，添加参数用于区别   1为一级评论   2为回复一级评论  3为回复二级评论
    public int commentType = 0;
    //情况为二级，评论时需要的被评论人的姓名和被评论文本的id
    public String beRepyedName = "";
    public String beReplyedId = "";
    public int parentCommentPosition = -1;

    public VideoDetailCommentPopup(Activity activity, View parentView, String videoInfoStr) {

        this.activity = activity;
        this.parentView = parentView;
        this.videoInfoStr = videoInfoStr;

        initPopuPopu();
    }

    private EasyPopup popu;

    private void initPopuPopu() {
        popu = EasyPopup.create()
                .setContext(activity)
                .setContentView(R.layout.popup_videodetail_comlist)
                .setWidth(WindowManager.LayoutParams.FILL_PARENT)
                .setHeight(WindowManager.LayoutParams.FILL_PARENT)
                .setOnViewListener(new EasyPopup.OnViewListener() {
                    @Override
                    public void initViews(View view, EasyPopup basePopup) {

                        if (StringUtil.isNotEmpty(videoInfoStr, true)) {
                            videoData = MGson.newGson().fromJson(videoInfoStr, ShareVideoDetailBean_1.ObjBean.RowsBean.class);
                        }

                        //初始化控件view
                        initView(view);

                        //初始化弹出框
                        initInputPopup();

                        //初始化评论数据
                        initCommentData();

                        //初始化评论列表控件
                        initCommentView();
                    }

                })
                .setFocusAndOutsideEnable(true)
                .apply();

    }

    private void initInputPopup() {

        //初始化输入框
        commentInputPopup = new BottomCommentPopup(activity);
        commentInputPopup.setBottomCommentListener(new BottomCommentPopup.BottomCommentListener() {
            @Override
            public void onSendMessage(String comment) {

                if (StringUtil.isNotEmpty(comment, true)) {

                    //如果当前输入为一级评论
                    if (1 == commentType) {

                        sendReplyCommentToService(comment);
                    } else if (2 == commentType) {//如果当前输入为评论二级评论

                        commentInputPopup.setInputHead(beRepyedName);
                        sendSecondReplyMsgToService(comment, "");
                    } else if (3 == commentType) {//如果当前输入为回复二级评论
                        commentInputPopup.setInputHead(beRepyedName);
                        sendSecondReplyMsgToService(comment, beReplyedId);
                    }
                }
            }
        });
    }

    private LinearLayout linComment;
    private ImageView ivBack, ivZan;
    private TextView tvZan, tvCommentNum;
    private CommentExpandableListView lvComment;
    private EditText etMsg;

    private View viewEmpty;

    private void initView(final View view) {

        ivBack = view.findViewById(R.id.iv_back);

        viewEmpty = view.findViewById(R.id.view_empty);

        lvComment = view.findViewById(R.id.lv_comment);
        tvCommentNum = view.findViewById(R.id.tv_commentnum);

        etMsg = view.findViewById(R.id.et_message);
        linComment = view.findViewById(R.id.lin_comment);
        ivZan = view.findViewById(R.id.iv_zan);
        tvZan = view.findViewById(R.id.tv_zan);

        linComment.setVisibility(View.GONE);

        viewEmpty.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        etMsg.setOnClickListener(this);
        ivZan.setOnClickListener(this);

        //设置顶部评论条数
        if (videoData.getComment_total() > -1) {
            tvCommentNum.setText(videoData.getComment_total() + "条评论");
        }

        //设置底部视频点赞数量
        if (videoData.getLike_total() > -1) {
            tvZan.setText(videoData.getLike_total() + "");
        }

        //设置底部视频点赞状态
        if (1 == videoData.getLike_status()) {
            ivZan.setImageResource(R.mipmap.circle_icon_like_s_have);
        } else if (0 == videoData.getLike_status()) {
            ivZan.setImageResource(R.mipmap.circle_icon_like_s_none);
        }
    }

    /**
     * 初始化评论和回复列表
     */
    private void initCommentView() {
        lvComment.setGroupIndicator(null);
        //默认展开所有回复
        commentAdapter = new CommentExpandAdapter(activity, commentsList);
        lvComment.setAdapter(commentAdapter);
        for (int i = 0; i < commentsList.size(); i++) {
            lvComment.expandGroup(i);
        }
        lvComment.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition, long l) {
                boolean isExpanded = expandableListView.isGroupExpanded(groupPosition);

                //设置为一级评论，并设置回复人名称
                commentType = 2;
                beRepyedName = commentsList.get(groupPosition).getUser_name();
                beReplyedId = commentsList.get(groupPosition).getComment_id() + "";
                commentAdapter.setReplyType(commentType);

                parentCommentPosition = groupPosition;

                LogUtil.e("onGroupClick: 当前的评论id>>>" + commentsList.get(groupPosition).getComment_id());
                if (isExpanded) {
                    //收起列表
                    expandableListView.collapseGroup(groupPosition);
                }
                expandableListView.expandGroup(groupPosition, true);

                if (parentView != null) {
                    if (StringUtil.isNotEmpty(beRepyedName, true)) {
                        commentInputPopup.setInputHead(beRepyedName);
                    }
                    commentInputPopup.showAnswerPopuPopu(parentView);
                }
                return true;
            }
        });

        lvComment.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long l) {
                commentType = 3;
                beRepyedName = commentsList.get(groupPosition).getSecondCommentBeans().get(childPosition).getUser_name();
                beReplyedId = commentsList.get(groupPosition).getSecondCommentBeans().get(childPosition).getReply_id() + "";
                commentAdapter.setReplyType(commentType);

                parentCommentPosition = groupPosition;

                if (parentView != null) {
                    if (StringUtil.isNotEmpty(beRepyedName, true)) {
                        commentInputPopup.setInputHead(beRepyedName);
                    }
                    commentInputPopup.showAnswerPopuPopu(parentView);
                }
                return false;
            }
        });

        lvComment.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                ToastManage.s(activity, "展开第" + groupPosition + "个分组");
            }
        });

    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.iv_back) {

            dismiss();
        } else if (i == R.id.et_message) {

            commentType = 1;
            if (parentView != null)
                commentInputPopup.showAnswerPopuPopu(parentView);

        } else if (i == R.id.iv_zan) {

            sendLikesToService(videoData.getDynamic_id());
        } else if (i == R.id.view_empty) {

            dismiss();
        }

    }

    public void dismiss() {
        popu.dismiss();
    }


    /**
     * 一级评论的数据
     */
    private void initCommentData() {

        LogUtil.e("请求接口时，dynamic_id的值为：" + videoData.getDynamic_id());
        if (videoData.getDynamic_id() != 0)
            HttpUtils.with(activity)
                    .addParam("requestType", "DYNAMIC_COMMENT_LIST_V2")
                    .addParam("dynamic_id", videoData.getDynamic_id())
                    .addParam("page", 0)
                    .addParam("limit", 10)
                    .addParam("token", SharedPreferenceManager.getInstance(activity).getUserCache().getUserToken())
                    .execute(new HttpNormalCallBack<VideoDetailCommentBean>() {
                        @Override
                        public void onSuccess(VideoDetailCommentBean result) {

                            if (CodeUtil.CODE_200 == result.getCode()) {

                                if (result.getObj().getRows().size() > 0 && result.getObj().getRows() != null) {

                                    if (commentsList.size() > 0) {
                                        commentsList.clear();
                                    }
                                    //根据一级评论的个数，获取所有回复的数据
                                    for (int i = 0; i < result.getObj().getRows().size(); i++) {
                                        initSecondCommentData(i, result.getObj().getRows().get(i).getComment_id());
                                    }
                                    commentsList.addAll(result.getObj().getRows());
                                    commentAdapter.notifyDataSetChanged();

                                }
                            }
                        }

                        @Override
                        public void onError(String e) {
                            LogUtil.e(e.toString());
                        }
                    });

    }

    /**
     * 二级评论的数据
     */
    private void initSecondCommentData(final int position, int beReplyId) {

        LogUtil.e("请求接口时，beReplyId的值为：" + beReplyId);
        if (beReplyId != 0)
            HttpUtils.with(activity)
                    .addParam("requestType", "DYNAMIC_REPLY_LIST")
                    .addParam("comment_id", beReplyId)
                    .addParam("page", 0)
                    .addParam("limit", 10)
                    .addParam("token", SharedPreferenceManager.getInstance(activity).getUserCache().getUserToken())
                    .execute(new HttpNormalCallBack<VideoDetailSecondCommentBean>() {
                        @Override
                        public void onSuccess(VideoDetailSecondCommentBean result) {

                            if (CodeUtil.CODE_200 == result.getCode()) {

                                if (result.getObj().getRows().size() > 0 && result.getObj().getRows() != null) {

                                    //将某一项的二级回复依次加入到总容器中
                                    for (int i = 0; i < result.getObj().getRows().size(); i++) {

                                        commentAdapter.addTheReplyData(result.getObj().getRows().get(i), position);
                                    }
                                }
                            }
                        }

                        @Override
                        public void onError(String e) {
                            LogUtil.e(e.toString());
                        }
                    });

    }

    /**
     * 发送一级评论消息至后台
     *
     * @param replyMsg
     */
    private void sendReplyCommentToService(String replyMsg) {

        HttpUtils.with(activity)
                .addParam("requestType", "DYNAMIC_COMMENT")
                .addParam("token", SharedPreferenceManager.getInstance(activity).getUserCache().getUserToken())
                .addParam("comment_content", replyMsg)
                .addParam("dynamic_id", videoData.getDynamic_id())
                .execute(new HttpDialogCallBack<ShareDetailWebReplyBean>() {
                    @Override
                    public void onSuccess(ShareDetailWebReplyBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            ToastManage.s(activity, result.getMsg());

                            if (result.getObj() != null) {

                                //将发布的数据装载进容器列表，并往适配器中插入一条数据
                                VideoDetailCommentBean.ObjBean.RowsBean rowsBean = new VideoDetailCommentBean.ObjBean.RowsBean();
                                rowsBean.setComment_id(result.getObj().getComment_id());
                                rowsBean.setComment_content(result.getObj().getComment_content());
                                rowsBean.setComment_date(result.getObj().getComment_date());
                                rowsBean.setUser_name(result.getObj().getUser_name());
                                rowsBean.setUser_icon(result.getObj().getUser_icon());
                                rowsBean.setLike_total(Integer.parseInt(result.getObj().getLike_total()));
                                rowsBean.setLike_status(Integer.parseInt(result.getObj().getLike_status()));
                                rowsBean.setReply_total(Integer.parseInt(result.getObj().getReply_total()));
                                rowsBean.setIs_author(Integer.parseInt(result.getObj().getIs_author()));

                                commentAdapter.addTheCommentData(rowsBean);
                            }
                        } else {
                            ToastManage.s(activity, result.getMsg());
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }

    /**
     * 发送二级评论数据至service
     *
     * @param comment     评论内容
     * @param beReplyedId 被回复的二级评论的id
     */
    private void sendSecondReplyMsgToService(String comment, String beReplyedId) {

        HttpUtils.with(activity)
                .addParam("requestType", "DYNAMIC_REPLY")
                .addParam("token", SharedPreferenceManager.getInstance(activity).getUserCache().getUserToken())
                .addParam("reply_content", comment)
                .addParam("comment_id", commentsList.get(parentCommentPosition).getComment_id())
                .addParam("up_reply_id", beReplyedId)
                .execute(new HttpDialogCallBack<ShareDetailSecondReplyBean>() {
                    @Override
                    public void onSuccess(ShareDetailSecondReplyBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            if (result != null) {

                                VideoDetailSecondCommentBean.ObjBean.RowsBean rowsBean = new VideoDetailSecondCommentBean.ObjBean.RowsBean();

                                //将发布的数据装载进容器列表，并往适配器中插入一条数据
                                rowsBean.setLike_total(result.getObj().getLike_status());
                                rowsBean.setLike_status(result.getObj().getLike_status());
                                rowsBean.setReply_type(result.getObj().getReply_type());
                                rowsBean.setBe_reply_user(result.getObj().getBe_reply_user());
                                rowsBean.setUser_name(result.getObj().getUser_name());
                                rowsBean.setUser_icon(result.getObj().getUser_icon());
                                rowsBean.setReply_id(result.getObj().getReply_id());
                                rowsBean.setReply_date(result.getObj().getReply_date());
                                rowsBean.setIs_author(result.getObj().getIs_author());
                                rowsBean.setUp_reply_id(result.getObj().getUp_reply_id() + "");
                                rowsBean.setReply_content(result.getObj().getReply_content());
                                rowsBean.setReply_status(result.getObj().getReply_type());

                                commentAdapter.addTheReplyData(rowsBean, parentCommentPosition);
                            }

                        } else {
                            ToastManage.s(activity, result.getMsg());
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });
    }

    /**
     * 发送点赞数据至后台
     *
     * @param dynamic_id
     */
    private void sendLikesToService(int dynamic_id) {

        LogUtil.e("请求DYNAMIC_LIKE接口时，dynamic_id的值为：" + dynamic_id);
        if (dynamic_id != 0)
            HttpUtils.with(activity)
                    .addParam("requestType", "DYNAMIC_LIKE")
                    .addParam("dynamic_id", dynamic_id)
                    .addParam("token", SharedPreferenceManager.getInstance(activity).getUserCache().getUserToken())
                    .execute(new HttpNormalCallBack<CircleLikesBean>() {
                        @Override
                        public void onSuccess(CircleLikesBean result) {

                            if (CodeUtil.CODE_200 == result.getCode()) {

                                int zan = result.getObj().getLike_status();

                                if (zan == 1) {
                                    ivZan.setImageResource(R.mipmap.circle_icon_like_s_have);
                                } else if (zan == 0) {
                                    ivZan.setImageResource(R.mipmap.circle_icon_like_s_none);
                                }
                                tvZan.setText(result.getObj().getLike_total() + "");
                                ToastManage.s(activity, result.getMsg());

                            } else {
                                ToastManage.s(activity, result.getMsg());
                            }
                        }

                        @Override
                        public void onError(String e) {
                            LogUtil.e(e.toString());
                        }
                    });

    }


    public void showAnswerPopuPopu(View view) {
        popu.showAtLocation(view, Gravity.TOP, 0, 0);

    }

    public interface VideoDetailCommentListener {
        void onDetailVideoMsg(String msg);
    }

    public VideoDetailCommentListener listener;

    public void setVideoDetailCommentListener(VideoDetailCommentListener videoDetailCommentListener) {
        this.listener = videoDetailCommentListener;
    }

}
